package com.ruoyi.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.page.Page;
import com.ruoyi.common.enums.YesNoEnum;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.MessReceive;
import com.ruoyi.system.domain.MessSend;
import com.ruoyi.system.mapper.MessReceiveMapper;
import com.ruoyi.system.service.IMessReceiveService;
import com.ruoyi.system.service.IMessSendService;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * APP收发消息Service业务层处理
 * 
 * @author wp
 * @date 2023-08-10
 */
@Service
public class MessReceiveServiceImpl extends ServiceImpl<MessReceiveMapper, MessReceive> implements IMessReceiveService {

    @Autowired
    private MessReceiveMapper messReceiveMapper;
    @Autowired
    private IMessSendService messSendService;

    @Override
    public List<MessReceive> selectList(MessReceive messReceive){
        return messReceiveMapper.list(messReceive);
    }

    @Override
    public List<MessReceive> getListBySendId(Long sendId){
        MessReceive messReceive = new MessReceive().setSendId(sendId);
        return selectList(messReceive);
    }

    @Transactional
    @Override
    public List<MessReceive> appSelectList(){
        List<MessReceive> messageList = messReceiveMapper.appList(new MessReceive().setReceiveUserId(SecurityUtils.getUserId()));
        //设置消息接收时间
        List<Long> receiveIds = messageList.stream().filter(i -> i.getReceiveTime() == null).map(MessReceive::getId).collect(Collectors.toList());
        if (ObjectUtils.isNotEmpty(receiveIds)){
            messReceiveMapper.update(new MessReceive().setReceiveTime(new Date()), new QueryWrapper<MessReceive>().in("id", receiveIds));
        }
        return messageList;
    }

    /**
     * 获取消息详情
     * @param id
     * @return
     */
    @Transactional
    @Override
    public MessSend getDetail(Long id){
        MessReceive receive = getById(id);
        if (receive.getIsRead() == YesNoEnum.NO.getCode()){
            receive.setIsRead(YesNoEnum.YES.getCode());
            receive.setReadTime(new Date());
            updateById(receive);
        }
        return messSendService.getById(receive.getSendId());
    }

    /**
     * 获取用户未读消息数量
     * @param receiveUserId
     * @return
     */
    @Override
    public int unreadMessageCount(Long receiveUserId){
        return messReceiveMapper.unreadMessageCount(receiveUserId);
    }

}
